﻿using Business.Base;
using Business.Common;
using Business.ScrewPump.Perf;
using Configuration;
using PLC;
using PLC.Base;
using Pumptester.ExperimentForms.Base;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace Pumptester.ExperimentForms.ScrewPump.Perf
{
    public partial class MainForm : Pumptester.ExperimentForms.Base.BaseMainForm
    {

        public MainForm(Experiment experiment) : base(experiment)
        {
            InitializeComponent();
            this.Experiment = experiment;
            //this.fetch_After = dataFetch_After;

            this.dataReadHandle = dataFetch_After;
        }


        /// <summary>
        /// 从硬件获取到数据后，计算，并且填入界面
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private void dataFetch_After(EnvData data)
        {
            this.textBoxJKYL.Text = data.PresureIn.ToString("F2");
            this.textBoxCKYL.Text = data.PresureOut.ToString("F2");
            this.textBoxSSLL.Text = data.Flow.ToString("F2");
            this.textBoxWD.Text = data.Temperature.ToString("F2");
            this.textBoxDJZS.Text = data.Speed.ToString("F2");
            this.textBoxDL.Text = data.Current.ToString("F2");
            this.textBoxDY.Text = data.Voltage.ToString("F2");
            this.textBoxYGGL.Text = (data.ShaftPower / 1000.0).ToString("F2");
            this.textBoxGLYS.Text = data.Powerfactor.ToString("F2");
            ScrewPumpPerfExperimentRecord record = (ScrewPumpPerfExperimentRecord)this.Service.CaculateDataFromRecord(data);
            this.textBoxGDZS.Text = ((ScrewPumpPerfExperiment)this.Experiment).DesignRatedSpeed.ToString();
            this.textBoxZHYL.Text = record.StpPresure.ToString("F2");
            this.textBoxZHLL.Text = record.StpFlow.ToString("F2");
            this.textBoxZHGL.Text = (record.StpPowerIn / 1000.0).ToString("F2");
            this.textBoxZGL.Text = (record.StpShaftPower / 1000.0).ToString("F2");
            this.textBoxJZXL.Text = record.StpGroupEfficiency.ToString("F2");
            this.textBoxXiaoLv.Text = record.StpPumpEfficiency.ToString("F2");
            this.textBoxSSZY.Text = record.PresureTotal.ToString("F2");


        }

        private void refreshIdCell()
        {
            for (int i = 0; i < this.dataGridView.Rows.Count; i++)
            {
                this.dataGridView.Rows[i].Cells[0].Value = i + 1;
            }
        }

        #region 继承的方法和属性

        private BaseService service = new ScrewPumpPerfExperimentService();


        protected override BaseService Service => service;

  

        protected override void DrawChart(BaseChartData chartData)
        {
            ScrewPumpPerfChartData chartDatainfo = (ScrewPumpPerfChartData)chartData;
            Axis axisPresureX = this.chart.ChartAreas["flowChart"].AxisX;
            Axis axisFlowY = this.chart.ChartAreas["flowChart"].AxisY;
            Axis axisPresureX2 = this.chart.ChartAreas["powerChart"].AxisX;
            Axis axisPowerY = this.chart.ChartAreas["powerChart"].AxisY;
            Axis axisPresureX3 = this.chart.ChartAreas["effChart"].AxisX;
            Axis axisEffY = this.chart.ChartAreas["effChart"].AxisY;

            axisPresureX.Maximum = chartDatainfo.MaxXPresureAxis;
            axisPresureX.Minimum = chartDatainfo.MinXPresureAxis;
            axisPresureX2.Maximum = chartDatainfo.MaxXPresureAxis;
            axisPresureX2.Minimum = chartDatainfo.MinXPresureAxis;
            axisPresureX3.Maximum = chartDatainfo.MaxXPresureAxis;
            axisPresureX3.Minimum = chartDatainfo.MinXPresureAxis;
            axisFlowY.Maximum = chartDatainfo.MaxYFlowAxis;
            axisFlowY.Minimum = chartDatainfo.MinYFlowAxis;
            axisPowerY.Maximum = chartDatainfo.MaxYPowerAxis;
            axisPowerY.Minimum = chartDatainfo.MinYPowerAxis;
            axisEffY.Maximum = 100.0; //后续统一到service中去
            axisEffY.Minimum = 0;

            axisPresureX.Interval = chartDatainfo.AxisXPresureInterval;
            axisPresureX2.Interval = chartDatainfo.AxisXPresureInterval;
            axisPresureX3.Interval = chartDatainfo.AxisXPresureInterval;
            axisFlowY.Interval = chartDatainfo.AxisYFlowInterval;
            axisPowerY.Interval = chartDatainfo.AxisYPowerInterval;
            axisEffY.Interval = chartDatainfo.AxisYEffInterval;


            chart.Series["PresureFlowCurve"].Points.Clear();
            chart.Series["PresurePowerCurve"].Points.Clear();
            chart.Series["PresureEffCurve"].Points.Clear();

            chart.Series["PresureFlowCurve"].Points.DataBindXY(chartDatainfo.DrawXPresureList, chartDatainfo.DrawYFlowList);
            chart.Series["PresurePowerCurve"].Points.DataBindXY(chartDatainfo.DrawXPresureList, chartDatainfo.DrawYPowerList);
            chart.Series["PresureEffCurve"].Points.DataBindXY(chartDatainfo.DrawXPresureList, chartDatainfo.DrawYEffList);
            chart.Series["PresureFlowPoint"].Points.Clear();
            chart.Series["PresurePowerPoint"].Points.Clear();
            chart.Series["PresureEffPoint"].Points.Clear();


            for (int i = 0; i < chartDatainfo.InputPresureFlowPoints.Count; i++)
            {
                double[] presureEffPoints = chartDatainfo.InputPresureEffPoints[i];
                double[] presurePowerPoints = chartDatainfo.InputPresurePowerPoints[i];
                double[] presureFlowPoints = chartDatainfo.InputPresureFlowPoints[i];
                chart.Series["PresureEffPoint"].Points.Add(new DataPoint(presureEffPoints[0], presureEffPoints[1]));
                chart.Series["PresurePowerPoint"].Points.Add(new DataPoint(presurePowerPoints[0], presurePowerPoints[1]));
                chart.Series["PresureFlowPoint"].Points.Add(new DataPoint(presureFlowPoints[0], presureFlowPoints[1]));
            }

            //chart.Series["流量扬程辅助判定线"].Points.Clear();
            //chart.Series["流量功率辅助判定线"].Points.Clear();
            //chart.Series["流量效率辅助判定线"].Points.Clear();
            //double[] zeroPoint = new double[] { 0, 0 };
            //double[] headPoint = new double[] { chartDatainfo.XRatedQ, chartDatainfo.YRatedHead };
            //double[] powerPoint = new double[] { chartDatainfo.XRatedQ, chartDatainfo.YRatedPower };
            //double[] effPoint = new double[] { chartDatainfo.XRatedQ, chartDatainfo.YRatedEff };

            ArrayList presureXList = new ArrayList();
            presureXList.Add(0.0f);
            presureXList.Add(chartDatainfo.XRatedPressure);
            ArrayList flowYList = new ArrayList();
            flowYList.Add(0.0f);
            flowYList.Add(chartDatainfo.YRatedFlow);
            ArrayList powerYList = new ArrayList();
            powerYList.Add(0.0f);
            powerYList.Add(chartDatainfo.YRatedPower);
            ArrayList effYList = new ArrayList();
            effYList.Add(0.0f);
            effYList.Add(chartDatainfo.YRatedEff);
            chart.Series["PresureFlowLine"].Points.DataBindXY(presureXList, flowYList);
            chart.Series["PresurePowerLine"].Points.DataBindXY(presureXList, powerYList);
            chart.Series["PresureEffLine"].Points.DataBindXY(presureXList, effYList);


            ArrayList xRatedPresureRange = new ArrayList();
            ArrayList xRatedFlowRange = new ArrayList();

            xRatedPresureRange.Add(chartDatainfo.PresureFlowRange[0, 0]);
            xRatedPresureRange.Add(chartDatainfo.PresureFlowRange[1, 0]);
            xRatedFlowRange.Add(chartDatainfo.PresureFlowRange[0, 1]);
            xRatedFlowRange.Add(chartDatainfo.PresureFlowRange[1, 1]);


            chart.Series["XPresureFlowRange"].Points.Clear();
            chart.Series["XPresureFlowRange"].Points.DataBindXY(xRatedPresureRange, xRatedFlowRange);





            ArrayList xRatedPresureRange2 = new ArrayList();
            ArrayList xRatedPowerRange = new ArrayList();

            xRatedPresureRange2.Add(chartDatainfo.PresurePowerRange[0, 0]);
            xRatedPresureRange2.Add(chartDatainfo.PresurePowerRange[1, 0]);
            xRatedPowerRange.Add(chartDatainfo.PresurePowerRange[0, 1]);
            xRatedPowerRange.Add(chartDatainfo.PresurePowerRange[1, 1]);

            chart.Series["YPresurePowerRange"].Points.Clear();
            chart.Series["YPresurePowerRange"].Points.DataBindXY(xRatedPresureRange2, xRatedPowerRange);


            ArrayList yRatedPresureRange3 = new ArrayList();
            ArrayList yRatedEffRange = new ArrayList();

            yRatedPresureRange3.Add(chartDatainfo.PresureEffRange[0, 0]);
            yRatedPresureRange3.Add(chartDatainfo.PresureEffRange[1, 0]);
            yRatedEffRange.Add(chartDatainfo.PresureEffRange[0, 1]);
            yRatedEffRange.Add(chartDatainfo.PresureEffRange[1, 1]);

         
            chart.Series["YPresureEffRange"].Points.Clear();
            chart.Series["YPresureEffRange"].Points.DataBindXY(yRatedPresureRange3, yRatedEffRange);





            /*chart.Series["流量扬程辅助判定线"].Points.Add(new DataPoint(zeroPoint[0],zeroPoint[1]));
            chart.Series["流量扬程辅助判定线"].Points.Add(new DataPoint(headPoint[0],headPoint[1]));

            chart.Series["流量功率辅助判定线"].Points.Add(new DataPoint(zeroPoint[0], zeroPoint[1]));
            chart.Series["流量功率辅助判定线"].Points.Add(new DataPoint(powerPoint[0], powerPoint[1]));


            chart.Series["流量效率辅助判定线"].Points.Add(new DataPoint(zeroPoint[0], zeroPoint[1])); 
            chart.Series["流量效率辅助判定线"].Points.Add(new DataPoint(effPoint[0], effPoint[1]));*/
        }



        protected override void ClearChart()
        {
            chart.Series["PresureEffPoint"].Points.Clear();
            chart.Series["PresurePowerPoint"].Points.Clear();
            chart.Series["PresureFlowPoint"].Points.Clear();    
        }

        protected override void DeleteSelectRecord()
        {

            DataGridViewSelectedRowCollection selectedRows = this.dataGridView.SelectedRows;

            if (selectedRows.Count == 0)
            {
                return;
            }

            int[] ids = new int[selectedRows.Count];

            for (int i = 0; i < selectedRows.Count; i++)
            {
                if (selectedRows[i].Tag == null)
                {
                    ids[i] = -1;
                    continue;
                }
                ScrewPumpPerfExperimentRecord record = (ScrewPumpPerfExperimentRecord)selectedRows[i].Tag;
                ids[i] = record.Id;
                this.dataGridView.Rows.Remove(selectedRows[i]);
                this.Experiment.RecordList.Remove(record);
            }
            this.Service.RemoveExperimentRecordByIds(ids);
            this.CaculateAndReDrawReport();
            this.dataGridView.ClearSelection();
            refreshIdCell();


        }

        protected override void DeleteAllRecord()
        {


            for (int i = 0; i < this.dataGridView.Rows.Count; i++)
            {
                object tag = this.dataGridView.Rows[i].Tag;
                if (tag != null)
                {
                    this.dataGridView.Rows[i].Selected = true;
                }

            }
            DeleteSelectRecord();

        }

        /*
        protected override void ShowReport()
        {
            this.splitContainer.Panel1Collapsed = true;
            this.toolStripButtonShowList.Visible = true;
            this.toolStripShowDataButton.Visible = false;
            this.toolStripButtonShowList.Enabled = true;
            this.toolStripShowDataButton.Enabled = false;
            this.tabControl.SelectedIndex = 1;
        }

        protected override void ShowList()
        {
            this.splitContainer.Panel1Collapsed = false;
            this.toolStripButtonShowList.Visible = false;
            this.toolStripShowDataButton.Visible = true;
            this.toolStripButtonShowList.Enabled = false;
            this.toolStripShowDataButton.Enabled = true;
            this.tabControl.SelectedIndex = 0;

        }*/

        protected override void SaveChart()
        {
            this.chart.SaveImage(Config.ExperimentChartImageDir + "\\" + Experiment.Code + ".png", System.Drawing.Imaging.ImageFormat.Png);
        }


        protected override ExperimentRecord assignEvnDataToRecord(EnvData data)
        {
            ScrewPumpPerfExperimentRecord record = (ScrewPumpPerfExperimentRecord)this.Service.CaculateDataFromRecord(data);
            return record;
        }

        protected override void ShowRecord(ExperimentRecord experimentRecord)
        {
            ScrewPumpPerfExperimentRecord record = (ScrewPumpPerfExperimentRecord)experimentRecord;

            record.ExperimentCode = this.Experiment.Code;
            DataGridViewRow row = (DataGridViewRow)this.dataGridView.RowTemplate.Clone();

            DataGridViewTextBoxCell idCell = new DataGridViewTextBoxCell();
            idCell.Value = 0;
            idCell.Tag = false;

            DataGridViewTextBoxCell workFlowCell = new DataGridViewTextBoxCell();
            workFlowCell.Value = record.WorkFlow.ToString("f6");
            workFlowCell.Tag = true;

            DataGridViewTextBoxCell presureInCell = new DataGridViewTextBoxCell();
            presureInCell.Value = record.PresureIn.ToString("f6");
            presureInCell.Tag = true;

            DataGridViewTextBoxCell presureOutCell = new DataGridViewTextBoxCell();
            presureOutCell.Value = record.PresureOut.ToString("f6");
            presureOutCell.Tag = true;

            DataGridViewTextBoxCell voltageCell = new DataGridViewTextBoxCell();
            voltageCell.Value = record.Voltage.ToString("f6");
            voltageCell.Tag = true;

            DataGridViewTextBoxCell electricCurrentCell = new DataGridViewTextBoxCell();
            electricCurrentCell.Value = record.ElectricCurrent.ToString("f6");
            electricCurrentCell.Tag = true;

            DataGridViewTextBoxCell powerCell = new DataGridViewTextBoxCell();
            powerCell.Value = (record.WorkingPower/1000.0).ToString("f6");
            powerCell.Tag = true;

            DataGridViewTextBoxCell workPresureCell = new DataGridViewTextBoxCell();
            workPresureCell.Value = record.PresureTotal.ToString("f6");
            workPresureCell.Tag = true;

            DataGridViewTextBoxCell speedCell = new DataGridViewTextBoxCell();
            speedCell.Value = record.WorkingSpeed.ToString("f6");
            speedCell.Tag = true;

            DataGridViewTextBoxCell temperatureCell = new DataGridViewTextBoxCell();
            temperatureCell.Value = record.Temperature.ToString("f6"); 
            temperatureCell.Tag = true;

             DataGridViewTextBoxCell stpQCell = new DataGridViewTextBoxCell();
            stpQCell.Value = record.StpFlow.ToString("f6");
            stpQCell.Tag = false;


            DataGridViewTextBoxCell stpPresureCell = new DataGridViewTextBoxCell();
            stpPresureCell.Value = record.StpPresure.ToString("f6");
            stpPresureCell.Tag = false;

            DataGridViewTextBoxCell stpShaftPowerCell = new DataGridViewTextBoxCell();
            stpShaftPowerCell.Value = (record.StpShaftPower/1000.0).ToString("f6");
            stpShaftPowerCell.Tag = false;

            DataGridViewTextBoxCell stpPumpEfficiencyCell = new DataGridViewTextBoxCell();
            stpPumpEfficiencyCell.Value = record.StpPumpEfficiency.ToString("f6");
            stpPumpEfficiencyCell.Tag = false;

            DataGridViewTextBoxCell stpGroupEfficiencyCell = new DataGridViewTextBoxCell();
            stpGroupEfficiencyCell.Value = record.StpGroupEfficiency.ToString("f6");
            stpGroupEfficiencyCell.Tag = false;


            DataGridViewTextBoxCell staticHeadCell = new DataGridViewTextBoxCell();
            staticHeadCell.Value = record.WorkingStaticHead.ToString("f6");
            staticHeadCell.Tag = false;

            DataGridViewTextBoxCell dynamicHeadHeadCell = new DataGridViewTextBoxCell();
            dynamicHeadHeadCell.Value = record.WorkingDynamicHead.ToString("f6");
            dynamicHeadHeadCell.Tag = false;


            DataGridViewTextBoxCell geoHeadHeadCell = new DataGridViewTextBoxCell();
            geoHeadHeadCell.Value = record.WorkingGeoHead.ToString("f6");
            geoHeadHeadCell.Tag = false;

            DataGridViewTextBoxCell frictionHeadCell = new DataGridViewTextBoxCell();
            frictionHeadCell.Value = record.WorkingFrictionHead.ToString("f6");
            frictionHeadCell.Tag = false;

            row.Cells.Add(idCell);
            row.Cells.Add(workFlowCell);
            row.Cells.Add(presureInCell);
            row.Cells.Add(presureOutCell);
            row.Cells.Add(voltageCell);
            row.Cells.Add(electricCurrentCell);
            row.Cells.Add(powerCell);
            row.Cells.Add(workPresureCell);
            row.Cells.Add(speedCell);
            row.Cells.Add(temperatureCell);
            row.Cells.Add(stpQCell);
            row.Cells.Add(stpPresureCell);
            row.Cells.Add(stpShaftPowerCell);
            row.Cells.Add(stpPumpEfficiencyCell);
            row.Cells.Add(stpGroupEfficiencyCell);
            row.Cells.Add(staticHeadCell);
            row.Cells.Add(dynamicHeadHeadCell);
            row.Cells.Add(geoHeadHeadCell);
            row.Cells.Add(frictionHeadCell);
            row.Tag = record;

            //this.experiment.RecordList.Add(record);
            this.dataGridView.Rows.Add(row);
            this.Service.SaveExperimentRecord(record);
            refreshIdCell();
            //计算和重画报表
            CaculateAndReDrawReport();
        }




        #endregion

   

  

        private void dataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView dataGridView = (DataGridView)sender;

            bool canSet = (bool)dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Tag;
            if (!canSet)
            {
                return;
            }

            String labelText = dataGridView.Columns[e.ColumnIndex].HeaderText;

            String oldValue = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
            DataGridViewRow row = dataGridView.Rows[e.RowIndex];

            ScrewPumpPerfExperimentRecord record = (ScrewPumpPerfExperimentRecord)row.Tag;
            ValueEditForm editForm = new ValueEditForm(labelText, oldValue);

            Point point = Control.MousePosition;
            editForm.Location = point;
            var result = editForm.ShowDialog();

            if (DialogResult.OK == result)
            {
                try
                {
                    dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = editForm.ReturnValue;

                }
                catch
                {
                    return;
                }
                switch (e.ColumnIndex)
                {
                    case 1: record.WorkFlow = Convert.ToDouble(editForm.ReturnValue); break;
                    case 2: record.PresureIn = Convert.ToDouble(editForm.ReturnValue); break;
                    case 3: record.PresureOut = Convert.ToDouble(editForm.ReturnValue); break;
                    case 4: record.Voltage = Convert.ToDouble(editForm.ReturnValue); break;
                    case 5: record.ElectricCurrent = Convert.ToDouble(editForm.ReturnValue); break;
                    case 6: record.WorkingPower = Convert.ToDouble(editForm.ReturnValue) * 1000.0; break;
                    case 7: record.PresureTotal = Convert.ToDouble(editForm.ReturnValue); break;
                    case 8: record.WorkingSpeed = Convert.ToDouble(editForm.ReturnValue); break;
                    case 9: record.Temperature = Convert.ToDouble(editForm.ReturnValue); break;
                }
                //重新计算
                EnvData data = new EnvData(record.PresureIn, record.PresureOut, record.WorkFlow, record.Temperature, record.WorkingSpeed, record.Voltage, record.ElectricCurrent, record.WorkingPower, Convert.ToDouble(this.textBoxGLYS.Text));
                ScrewPumpPerfExperimentRecord newRecord = (ScrewPumpPerfExperimentRecord)this.Service.CaculateDataFromRecord(data);

                //重新刷新数据
                record.StpFlow = newRecord.StpFlow;
                record.StpPresure = newRecord.StpPresure;
                record.StpShaftPower = newRecord.StpShaftPower;
                record.StpPumpEfficiency = newRecord.StpPumpEfficiency;
                record.StpGroupEfficiency = newRecord.StpGroupEfficiency;
                record.WorkingStaticHead = newRecord.WorkingStaticHead;
                record.WorkingDynamicHead = newRecord.WorkingDynamicHead;
                record.WorkingGeoHead = newRecord.WorkingGeoHead;
                record.WorkingFrictionHead = newRecord.WorkingFrictionHead;

                dataGridView.Rows[e.RowIndex].Cells[10].Value = record.StpFlow.ToString("F6");
                dataGridView.Rows[e.RowIndex].Cells[11].Value = record.StpPresure.ToString("F6"); ;
                dataGridView.Rows[e.RowIndex].Cells[12].Value = record.StpShaftPower.ToString("F6"); ;
                dataGridView.Rows[e.RowIndex].Cells[13].Value = record.StpPumpEfficiency.ToString("F6"); ;
                dataGridView.Rows[e.RowIndex].Cells[14].Value = record.StpGroupEfficiency.ToString("F6");
                dataGridView.Rows[e.RowIndex].Cells[15].Value = record.WorkingStaticHead.ToString("F6");
                dataGridView.Rows[e.RowIndex].Cells[16].Value = record.WorkingDynamicHead.ToString("F6");
                dataGridView.Rows[e.RowIndex].Cells[17].Value = record.WorkingGeoHead.ToString("F6");
                dataGridView.Rows[e.RowIndex].Cells[18].Value = record.WorkingFrictionHead.ToString("F6");
                CaculateAndReDrawReport();

            }

        }
    }
}
